/*
 * JasperReports - Free Java Reporting Library.
 * Copyright (C) 2001 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com
 *
 * Unless you have purchased a commercial license agreement from Jaspersoft,
 * the following license terms apply:
 *
 * This program is part of JasperReports.
 *
 * JasperReports is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JasperReports is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
 */
package com.ssc.jasperttest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.data.JRXlsDataSource;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRXhtmlExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.oasis.JROdsExporter;
import net.sf.jasperreports.engine.export.oasis.JROdtExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.util.AbstractSampleApp;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;
import org.eclipse.core.runtime.Path;
import org.eclipse.osgi.service.datalocation.Location;

import com.ssc.shalomsoft.Activator;

/**
 * @author
 * @version $Id: XlsDataSourceApp.java 4595 2011-09-08 15:55:10Z teodord $
 */
public class AnnuaireApp extends AbstractSampleApp {

	
	private File installFolder;
	private File reportTemplateFile;
	private File jrPrintFile;
	private String outputFolder;

	public AnnuaireApp() {
		try {
			//if(!DEBUG){
				
				Location installLocation = Platform.getInstallLocation();
				URL u = installLocation.getURL();
				installFolder = new File(u.getPath());
				reportTemplateFile = new File(installFolder, "reports/Annuaire.jasper");
//			}
//			else {
//				Bundle bundle = FrameworkUtil.getBundle(this.getClass());
//				URL url = FileLocator.find(bundle, new Path(
//						"reports/Annuaire.jasper"), null);
//				reportTemplateFile = new File(url.getFile());
//				System.out.println("Is file :"+ reportTemplateFile.isFile());
//				
//			}

		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
	}

	private InputStream initJaspertPrintFile() {
		InputStream result = null;
		try {

			jrPrintFile = new File(installFolder, "reports/Annuaire.jrprint");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 *
	 */
	public static void main(String[] args) {
		main(new AnnuaireApp(), new String[] { "test" });
	}

	/**
	 *
	 */
	public void test() throws JRException {
	}

	public void test(String fichier) throws JRException {
		// fill();
		fill2(fichier);
		pdf();
		// xmlEmbed();
		// xml();
		// html();
		 rtf();
		// xls();
		// jxl();
		// csv();
		// odt();
		// ods();
		// docx();
		// xlsx();
		// pptx();
		// xhtml();
	}

	/**
	 *
	 */
	public void fill() throws JRException {
		long start = System.currentTimeMillis();
		// Preparing parameters
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("ReportTitle", "Address Report");
		parameters.put("DataFile", "Annuaire.xls - XLS data source");
		Set<String> states = new HashSet<String>();
		states.add("Active");
		states.add("Trial");
		parameters.put("IncludedStates", states);

		JasperFillManager.fillReportToFile("reports/Annuaire.jasper", parameters, getDataSource());
		System.err.println("Filling time : " + (System.currentTimeMillis() - start));
	}

	public void fill2(String fichier) throws JRException {
		long start = System.currentTimeMillis();
		// Preparing parameters
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("ReportTitle", "Address Report");
		parameters.put("DataFile", "Annuaire.xls - XLS data source");
		Set<String> states = new HashSet<String>();
		states.add("Active");
		states.add("Trial");
		parameters.put("IncludedStates", states);

		JasperFillManager.fillReportToFile(reportTemplateFile.getPath(), parameters, getDataSource2(fichier));
		System.err.println("Filling time : " + (System.currentTimeMillis() - start));
	}

	private static String toStringRemoveNull(Object o) {
		if (o == null || String.valueOf(o).equals("null"))
			return "";
		else
			return String.valueOf(o);
	}

	/**
	 *
	 */
	private static JRBeanCollectionDataSource getDataSource2(String fileName) throws JRException {
		JRBeanCollectionDataSource ds = null;
		InputStream inp = null;
		try {
			AdherentList adherentList = new AdherentList();
			AdherentAnnuaireBeanList adherentAnnuaireBeanList = new AdherentAnnuaireBeanList();
			inp = new FileInputStream(fileName);

			Workbook wb = WorkbookFactory.create(inp);
			Sheet sheet = wb.getSheetAt(0);
			for (Row row : sheet) {
				if (row.getRowNum() == 0)
					continue;

				Adherent currentAdherent = new Adherent();
				for (Cell cell : row) {
					if (cell.getColumnIndex() == 0 || cell.getColumnIndex() == 1)
						continue;
					switch (cell.getColumnIndex()) {
					case 2: {
						currentAdherent.setCivilite(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 3: {
						currentAdherent.setNom(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 4: {
						currentAdherent.setPrenom(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 5: {
						currentAdherent.setCommentaire(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 6: {
						currentAdherent.setAdresse1(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 7: {
						currentAdherent.setAdresse2(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 8: {
						String codepostal = null;
						try {
							codepostal = toStringRemoveNull(String.valueOf(Math.round(cell.getNumericCellValue())));
							if("0".equals(codepostal)) codepostal="";
							//currentAdherent.setCodePostal(codepostal);
						} catch (IllegalStateException e) {
							codepostal = toStringRemoveNull(String.valueOf(cell.getRichStringCellValue()));
						}
						finally {
							currentAdherent.setCodePostal(codepostal);
							
						}
						break;
					}
					case 9: {
						currentAdherent.setVille(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 10: {
						try {
							currentAdherent.setFixe1(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						} catch (IllegalStateException e) {
							currentAdherent.setFixe1(toStringRemoveNull(String.valueOf(cell.getNumericCellValue())));
						}
						break;
					}
					case 11: {
						try {
							currentAdherent.setFixe2(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						} catch (IllegalStateException e) {
							currentAdherent.setFixe2(toStringRemoveNull(String.valueOf(cell.getNumericCellValue())));
						}

						break;
					}
					case 12: {
						try {
							currentAdherent.setPort1(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						} catch (IllegalStateException e) {
							currentAdherent.setPort1(toStringRemoveNull(String.valueOf(cell.getNumericCellValue())));
						}
						break;
					}
					case 13: {
						try {
							currentAdherent.setPort2(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						} catch (IllegalStateException e) {
							currentAdherent.setPort2(toStringRemoveNull(String.valueOf(cell.getNumericCellValue())));
						}
						break;
					}
					case 14: {
						try {
							currentAdherent.setPort3(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						} catch (IllegalStateException e) {
							currentAdherent.setPort3(toStringRemoveNull(String.valueOf(cell.getNumericCellValue())));
						}
						break;
					}
					case 15: {
						currentAdherent.setEmail1(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}
					case 16: {
						currentAdherent.setEmail2(toStringRemoveNull(cell.getRichStringCellValue().getString()));
						break;
					}

					}
				}

				if (currentAdherent.getNom() != null && currentAdherent.getPrenom() != null)
					adherentList.add(currentAdherent);
			}
			for (Adherent adh : adherentList.getReadOnlyInternList()) {
				adherentAnnuaireBeanList.add(new AdherentAnnuaireBean(adh));
			}
			ds = new JRBeanCollectionDataSource(adherentAnnuaireBeanList.getReadOnlyInternList());
			inp.close();
		} catch (Exception excepion) {
			excepion.printStackTrace();
		} finally {
			if (inp != null) {
				try {
					inp.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}

		return ds;
	}

	/**
	 *
	 */
	public void print() throws JRException {
		long start = System.currentTimeMillis();
		JasperPrintManager.printReport("reports/Annuaire.jrprint", true);
		System.err.println("Printing time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void pdf() throws JRException {
		try {
			long start = System.currentTimeMillis();

			initJaspertPrintFile();

			JasperExportManager.exportReportToPdfFile(jrPrintFile.getPath(), new File(outputFolder, "Annuaire.pdf").getPath());
			// pdfOutPutStream.close();

			JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(jrPrintFile);

			File destFile = new File(outputFolder, "Annuaire.rtf");

			JRRtfExporter exporter = new JRRtfExporter();

			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

			exporter.exportReport();

			System.err.println("PDF creation time : " + (System.currentTimeMillis() - start));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 *
	 */
	public void xml() throws JRException {
		long start = System.currentTimeMillis();
		JasperExportManager.exportReportToXmlFile("reports/Annuaire.jrprint", false);
		System.err.println("XML creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void xmlEmbed() throws JRException {
		long start = System.currentTimeMillis();
		JasperExportManager.exportReportToXmlFile("reports/Annuaire.jrprint", true);
		System.err.println("XML creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void html() throws JRException {
		long start = System.currentTimeMillis();
		JasperExportManager.exportReportToHtmlFile("reports/Annuaire.jrprint");
		System.err.println("HTML creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void rtf() throws JRException {
		long start = System.currentTimeMillis();
		
		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(jrPrintFile);

		File destFile = new File(outputFolder, "Annuaire.rtf");

		JRRtfExporter exporter = new JRRtfExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

		exporter.exportReport();

		System.err.println("RTF creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void xls() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".xls");

		JRXlsExporter exporter = new JRXlsExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());
		exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);

		exporter.exportReport();

		System.err.println("XLS creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void jxl() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".jxl.xls");

		JExcelApiExporter exporter = new JExcelApiExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());
		exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);

		exporter.exportReport();

		System.err.println("XLS creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void csv() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".csv");

		JRCsvExporter exporter = new JRCsvExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

		exporter.exportReport();

		System.err.println("CSV creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void odt() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".odt");

		JROdtExporter exporter = new JROdtExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

		exporter.exportReport();

		System.err.println("ODT creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void ods() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".ods");

		JROdsExporter exporter = new JROdsExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());
		exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);

		exporter.exportReport();

		System.err.println("ODS creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void docx() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".docx");

		JRDocxExporter exporter = new JRDocxExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

		exporter.exportReport();

		System.err.println("DOCX creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void xlsx() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".xlsx");

		JRXlsxExporter exporter = new JRXlsxExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());
		exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);

		exporter.exportReport();

		System.err.println("XLSX creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void pptx() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".pptx");

		JRPptxExporter exporter = new JRPptxExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

		exporter.exportReport();

		System.err.println("PPTX creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	public void xhtml() throws JRException {
		long start = System.currentTimeMillis();
		File sourceFile = new File("reports/Annuaire.jrprint");

		JasperPrint jasperPrint = (JasperPrint) JRLoader.loadObject(sourceFile);

		File destFile = new File(sourceFile.getParent(), jasperPrint.getName() + ".x.html");

		JRXhtmlExporter exporter = new JRXhtmlExporter();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFile.toString());

		exporter.exportReport();

		System.err.println("XHTML creation time : " + (System.currentTimeMillis() - start));
	}

	/**
	 *
	 */
	private static JRXlsDataSource getDataSource() throws JRException {
		JRXlsDataSource ds;

		try {
			String[] columnNames = new String[] { "civilite", "nom", "prenom", "commentaire", "adresse1", "adresse2", "codePostal", "ville", "fixe1",
					"fixe2", "port1", "port2", "port3", "email1", "email2" };
			int[] columnIndexes = new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
			ds = new JRXlsDataSource(JRLoader.getLocationInputStream("data/Annuaire.xls"));
			// ds.setUseFirstRowAsHeader(true);
			ds.setColumnNames(columnNames, columnIndexes);
		} catch (IOException e) {
			throw new JRException(e);
		}

		return ds;
	}

	public void setOutputFolder(String text) {

		this.outputFolder = text;
	}

}
